package com.zt.csp.shorturl.controller;

import com.zt.csp.shorturl.utils.NetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * HTML页面渲染，提供简单页面展示。这层只负责渲染页面，不负责业务逻辑，所有业务全部走AJax请求。
 * Created by zt on 2018/4/17 0017
 */

@PropertySource("classpath:application.yml")
@Controller
public class HtmlController {
    private static final Logger logger = LoggerFactory.getLogger(HtmlController.class);

    @Value("a")
    private String host;

    @Value("b")
    private String appId;

    /**
     * 项目主页，主要提供了本项目的介绍和短链接体验
     *
     * @return 前端页面名称，index表示/resources/templates/index.ftl，在application.yml里面配置freemarker相关的参数
     */
    @RequestMapping("/")
    public String index(HttpServletRequest request) throws IOException {
        logger.info("IP[{}]访问了首页", NetworkUtil.getIpAddress(request));
        return "index";
    }

    /**
     * 用户登录界面，对接了用户权限中心
     *
     * @param request 传递一些基本参数，用户权限中心的host和appId
     * @return login页面名称，位于：resources/templates/login.ftl
     */
    @RequestMapping("/user/login")
    public String login(HttpServletRequest request, @RequestParam(required = false) String redirectUrl) {
        request.setAttribute("host", host);
        request.setAttribute("appId", appId);
        if (StringUtils.isEmpty(redirectUrl)) {
            redirectUrl = "/";
        }
        request.setAttribute("redirectUrl", redirectUrl);
        return "login";
    }

    /**
     * 短链接列表页面，管理短链接
     *
     * @return 页面名称，位于：resources/templates/list.ftl
     */
    @RequestMapping("/short/list")
    public String list() {
        return "list";
    }

    /**
     * 短链接访问日志
     *
     * @return 页面名称，位于：resources/templates/log.ftl
     */
    @RequestMapping("/short/{shortUrlCode}/log")
    public String log(HttpServletRequest request, @PathVariable String shortUrlCode) {
        request.setAttribute("shortUrlCode", shortUrlCode);
        return "log";
    }

}
